package com.example.noactivityresult;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), activityResult -> {
            String result1 = activityResult.getData().getStringExtra("result");
            Toast.makeText(this, "获取结果：" + result1, Toast.LENGTH_SHORT).show();
        });
        findViewById(R.id.click).setOnClickListener(v -> {
            Intent intent = new Intent(this, SecondActivity.class);
            intent.putExtra("str", "sasdadsd");
            launcher.launch(intent);
//           launcher.launch("Hello,技术最TOP");
        });

        findViewById(R.id.click3).setOnClickListener(v -> {
            startActivity(new Intent(this, ThirdActivity.class));
        });
    }

    ActivityResultLauncher launcher = registerForActivityResult(new MyResultContract(), result -> {
        Toast.makeText(this, "获取结果：" + result, Toast.LENGTH_SHORT).show();


    });

    class MyResultContract extends ActivityResultContract<String, String> {

        @NonNull
        @Override
        public Intent createIntent(@NonNull Context context, String input) {
            Intent intent = new Intent(context, SecondActivity.class);
            intent.putExtra("str", input);
            return intent;
        }

        @Override
        public String parseResult(int resultCode, @Nullable Intent intent) {
            return intent.getStringExtra("result");
        }
    }
}